import { useEffect, useRef, useState } from 'react';
import styles from './index.module.less';

interface Props {
  onMove: (forward: number, turn: number) => void;
  maxRadius?: number;
};

const getMousePosition = (event: any) => {
  let clientX = event.targetTouches ? event.targetTouches[0].pageX : event.clientX;
  let clientY = event.targetTouches ? event.targetTouches[0].pageY : event.clientY;
  return {
    x: clientX,
    y: clientY
  };
}

const JoyStick = (props: Props) => {
  const { maxRadius = 40 } = props;
  const thumbRef = useRef<any>(null);
  const originRef = useRef({ left: 0, top: 0 });
  const offsetRef = useRef({ x: 0, y: 0 });
  const [thumbStyle, setThumbStyle] = useState({});

  const maxRadiusSquared = maxRadius * maxRadius;

  const handlerMove = (event: any) => {
    const mouse = getMousePosition(event);
    // 计算新的鼠标位置
    let left = mouse.x - offsetRef.current.x;
    let top = mouse.y - offsetRef.current.y;
    const sqMag = left * left + top * top;
    if (sqMag > maxRadiusSquared) {
      const magnitude = Math.sqrt(sqMag);
      left /= magnitude;
      top /= magnitude;
      left *= maxRadius;
      top *= maxRadius;
    }
    // 设置元素新的位置
    setThumbStyle({
      top: `${top + thumbRef.current.clientHeight/2}px`,
      left: `${left + thumbRef.current.clientWidth/2}px`
    });
    const forward = -(top - originRef.current.top + thumbRef.current.clientHeight / 2) / maxRadius;
    const turn = (left - originRef.current.left + thumbRef.current.clientWidth / 2) / maxRadius;
    props.onMove(forward, turn);
    // if (this.onMove !== undefined) this.onMove.call(this.game, forward, turn);
  };

  const handlerMoveEnd = () => {
    if ('ontouchstart' in window) {
      document.removeEventListener('touchmove', handlerMove);
      document.removeEventListener('touchend', handlerMoveEnd);
    } else {
      document.removeEventListener('mousemove', handlerMove);
      document.removeEventListener('mouseup', handlerMoveEnd);
    }
    setThumbStyle({
      left: `${originRef.current.top}px`,
      top: `${originRef.current.left}px`
    });
    props.onMove(0, 0);
    // this.onMove.call(this.game, 0, 0);
  };

  const handlerTap = (event: any) => {
    offsetRef.current = getMousePosition(event);
    if ('ontouchstart' in window) {
      document.addEventListener('touchmove', handlerMove);
      document.addEventListener('touchend', handlerMoveEnd);
    } else {
      document.addEventListener('mousemove', handlerMove);
      document.addEventListener('mouseup', handlerMoveEnd);
    }
  };

  useEffect(() => {
    originRef.current = {
      left: thumbRef.current.offsetLeft,
      top: thumbRef.current.offsetTop
    };
  }, []);

  return (
    <div className={styles.circle}>
      <div onTouchStart={handlerTap} style={thumbStyle} onMouseDown={handlerTap} ref={thumbRef} className={styles.thumb}></div>
    </div>
  );
};

export default JoyStick;